daemon()

Jim Wright (jwright@cfht.hawaii.edu)
Thu, 24 Feb 1994 08:42:10 -1000

> Date: Thu, 24 Feb 1994 15:32:46 +1100 (EST)
> From: "Julian Assange" <proff@suburbia.apana.org.au>
>
> my version of daemon():
>
> void daemon()
> {
> 	close(0);
> 	close(1);
> 	close(2);
> 	setsid();
> 	if (fork()) _exit(0);
> }

I offer this and ask for critiques.


/*!****************************************************************************
* FILE
* $Header: cfht_goDaemon.c,v 1.6 93/03/04 20:50:05 jwright Exp $
* $Locker:  $
*
* ROUTINES
*    cfht_goDaemon()
*        Disconnect from the world and become a daemon process.
*
*    INVOKED
*        cfht_goDaemon();
*
*    PARAMETERS IN
*        none
*
*    PARAMETERS OUT
*        none
*
*    FUNCTION RETURNS
*        none
*
*    GLOBALS
*        none
*
****************************************************************************!*/

#include <fcntl.h>
#include <unistd.h>
#include <cfht/cfht.h>	/* for calls to our logging system */

void
cfht_goDaemon ()
{
    int i;
    int f;
    int status;

    /* become a child, make parent exit */
    status = fork();
    if (status < 0) {
	/* fork call failed, no child, we are parent */
        cfht_log (CFHT_MAIN, CFHT_ERRNO,
	      "(cfht_goDaemon) can't fork a new process for daemon");
	exit (-1);
    } else if (status > 0) {
	/* we are the parent, bail out and let child continue */
	exit (0);
    }
    /* we are the child, keep on going */

    /* how many files to close? */
#ifdef hpux
    f = sysconf (_SC_OPEN_MAX);
#else
#ifdef sun
    f = getdtablesize ();
#else
    SHOW ME HOW TO GET MAX NUMBER OF OPEN FILES PER PROCESS
#endif
#endif

    /* disassociate from controlling terminal */
    if (setsid() == -1) {
        cfht_log (CFHT_MAIN, CFHT_ERRNO,
	      "(cfht_goDaemon) can't disassociate from controlling terminal");
        /* continue execution, hope for the best */
	/* is this bad?  should we bail out? */
    }

    /* close all fd's */
    for (i = 0; i < f; i++)
        close (i);

    /* attach 0,1,2 to /dev/null */
    open ("/dev/null", O_RDONLY);
    dup2 (0, 1);
    dup2 (0, 2);
}